package base.core.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 文件压缩工具
 * Pengwei
 * 2022/3/9 22:26
 */

public class ZipUtils {

    /**
     * 将 String 添加进压缩包
     *
     * @param zipOutputStream
     * @param insidePath      文件在压缩包中的路径
     * @param fileName        要压缩的文件名
     * @param content         文件内容
     */
    public static void zip(ZipOutputStream zipOutputStream, String insidePath, String fileName, byte[] content) throws IOException {
        zipOutputStream.putNextEntry(new ZipEntry(insidePath.replaceAll("/*$", "") + "/" + fileName));
        zipOutputStream.write(content);
    }

    /**
     * 压缩文件或文件夹
     * @param zipOutputStream
     * @param file 压缩的文件或文件夹
     */
    public static void zipFile(ZipOutputStream zipOutputStream, File file) throws IOException {
        //遍历文件或文件夹
        eachFile(zipOutputStream, file, file);
    }

    /**
     * 压缩文件或者文件夹
     * @param zipOutputStream
     * @param file            被压缩的文件,或者文件夹
     * @param rootFile        根文件
     * @throws IOException
     */
    private static void eachFile(ZipOutputStream zipOutputStream, File file, File rootFile) throws IOException {
        //文件或者文件夹不存在
        if (file == null || !file.exists()) {
            return;
        }
        String insideFilePath = file.getAbsolutePath().replace(rootFile.getParentFile().getAbsolutePath(), "");
        //是文件,则将文件写进zip
        if (file.isFile()) {
            zipOutputStream.putNextEntry(new ZipEntry(insideFilePath));
            FileInputStream inputStream = new FileInputStream(file);
            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) > 0) {
                zipOutputStream.write(bytes, 0, len);
            }
            inputStream.close();
            return;
        }
        //是文件夹
        if (file.isDirectory()) {
            zipOutputStream.putNextEntry(new ZipEntry(insideFilePath + "/"));
            File[] files = file.listFiles();
            for (File childFile : files) {
                eachFile(zipOutputStream, childFile, rootFile);
            }
        }
    }
}